/**
 * 
 */
package com.witframework.validator;

/**
 * @author wuxinyang Sep 27, 2009 4:19:20 PM
 */

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validation implements IValidation {
	protected Pattern acceptedPattern;
	protected Pattern rejectedPattern;
	private Map ignoreParametersMap;
	private String message;

	public void setIgnoreParameters(List ignoreParameters) {
		this.ignoreParametersMap = new Hashtable();

		for (int i = 0; i < ignoreParameters.size(); ++i) {
			String currentIgnoreParameter = (String) ignoreParameters.get(i);
			this.ignoreParametersMap.put(currentIgnoreParameter, currentIgnoreParameter);
		}
	}

	public boolean existIgnoreParameters() {
		return ((this.ignoreParametersMap != null) && (this.ignoreParametersMap.size() > 0));
	}

	public boolean isIgnoreParameter(String parameter) {
		return this.ignoreParametersMap.containsKey(parameter);
	}

	public boolean validate(String parameter, String value) {
		Pattern p = null;
		Matcher m = null;
		if ((existIgnoreParameters()) && (isIgnoreParameter(parameter))) {
			return true;
		}

		if (this.acceptedPattern != null) {
			m = this.acceptedPattern.matcher(value);
			if (!(m.matches())) {
				return false;
			}
		}

		if (this.rejectedPattern != null) {
			m = this.rejectedPattern.matcher(value);

			if (m.matches()) {
				return false;
			}
		}
		return true;
	}

	public boolean validate(String parameter, String[] values) {
		Pattern p = null;
		Matcher m = null;
		if ((existIgnoreParameters()) && (isIgnoreParameter(parameter))) {
			return true;
		}

		for (int j = 0; j < values.length; ++j) {
			if (this.acceptedPattern != null) {
				m = this.acceptedPattern.matcher(values[j]);

				if (!(m.matches())) {
					return false;
				}
			}

			if (this.rejectedPattern == null)
				continue;
			m = this.rejectedPattern.matcher(values[j]);

			if (m.matches()) {
				return false;
			}
		}

		return true;
	}

	public void setAcceptedPattern(String acceptedPattern) {
		this.acceptedPattern = Pattern.compile(acceptedPattern);
	}

	public void setRejectedPattern(String rejectedPattern) {
		this.rejectedPattern = Pattern.compile(rejectedPattern);
	}

	public String message() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}